﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Client.Commands;
using Client.Processes;
using Client.Resources;
using Contracts.Entities;

namespace Client.ViewModels.WebImport
{
    public class SearchImportViewModel : WizardPageViewModel
    {
        #region Init

        private IEnumerable<MovieItem> baseItems;
        private IEnumerable<MovieItem> importItems;
        private ImportWebInfos import;
        private string log;
        private int result;
        private string info;
        private bool importCompleted;
        private bool isBusy;
        private int requests;

        public SearchImportViewModel(IEnumerable<MovieItem> baseItems)
        {
            this.baseItems = baseItems;
            import = new ImportWebInfos();
            import.OnResult += LogResult;
        } 

        #endregion

        #region Properties

        public ICommand ImportCommand 
        {
            get
            {
                return new RelayCommand(() => Import(), () => !isBusy);
            }
        }

        public string Log
        {
            get
            {
                return log;
            }
            set
            {
                log = value;
                NotifyPropertyChanged("Log");
            }
        }

        public string Info
        {
            get
            {
                return info;
            }
            set
            {
                info = value;
                NotifyPropertyChanged("Info");
            }
        }

        public bool IsBusy
        {
            get
            {
                return isBusy;
            }
            set
            {
                isBusy = value;
                NotifyPropertyChanged("IsBusy");
            }
        }

        #endregion

        #region Processes

        private void Import()
        {
            result = 0;
            importCompleted = false;
            IsBusy = true;

            importItems = baseItems.Where(m => !String.IsNullOrEmpty(m.TmdbId));
            requests = importItems.Distinct(new MovieNameComparer()).Count();

            Log += String.Format("Importieren wird ausgeführt...{0}", Environment.NewLine);          
            LogProgress();

            import.Process(importItems);             
        }

        /// <summary>
        /// Protokllieren des Fortschritts
        /// </summary>
        private void LogProgress()
        {
            Info = String.Format("{0}/{1} Film(e) importiert", result, requests);           
        }

        /// <summary>
        /// Protokollieren eines erflogreich importierten Films
        /// </summary>
        /// <param name="movieName"></param>
        public void LogResult(TmdbResult response)
        {
            result++;
            LogProgress();

            if (response.Success)
                Log += String.Format("{0} Informationen zu \"{1}\" wurden heruntergeladen und gespeichert {2}",                                         
                    DateTime.Now.ToShortTimeString(),              
                    response.Request,                                        
                    Environment.NewLine);
            else
                Log += String.Format("{0} Beim Importieren der Informationen zu \"{1}\" ist ein Fehler aufgetreten {2}",
                    DateTime.Now.ToShortTimeString(),
                    response.Request,
                    Environment.NewLine);

            if (result == requests)
                FinishImport();
        }

        private void FinishImport()
        {
            Log += String.Format("{0}Importieren beendet{1}", 
                Environment.NewLine, Environment.NewLine);

            IsBusy = false; 
            importCompleted = true;
            CommandManager.InvalidateRequerySuggested();
        }

        #endregion

        #region WebImportBaseViewModel Member

        public override bool IsValid()
        {
            return importCompleted;
        }

        public override string GetButtonNextContent()
        {
            return "Fertig stellen";
        }

        public override event Action<object> OnResult = m => { };
       
        /// <summary>
        /// TmdbID wird gesetzt für importierendes Element
        /// Für alle doppelte Filme wird TmdbId gesetzt,
        /// wenn erneut zugewiesen, dann String.Empty (entspricht in View abgewählt)
        /// </summary>
        public override void Process(object data)
        {
            var item = data as MovieItem;

            var results = baseItems.Where(m => m.Name == item.Name);

            foreach (var result in results)
            {
                if (String.IsNullOrEmpty(result.TmdbId))
                    result.TmdbId = item.TmdbId;

                else if (item.TmdbId == result.TmdbId)
                    result.TmdbId = String.Empty;

                else
                    result.TmdbId = item.TmdbId;
            }
        }

        #endregion        
        
    }
}
